/*
 * Copyright (C) 2018 Baidu, Inc. All Rights Reserved.
 */
package com.baidu.util;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;

/**。
 * 用于将showx传来的json格式的参数，转为对应的参数对象
 *
 * @author zhangcixiao
 */
public class JsonDataParser {

    public static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * json字符串转为object
     * {"a": 1}
     *
     * @param param
     * @param type
     * @return
     */
    public static <T> T toObject(String param, Class<T> type) {
        T t = null;
        try {
            t = objectMapper.readValue(param, type);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * json字符串转为List
     * ["a", "b", "c"]
     *
     * @param param
     * @param type
     * @return
     */
    public static <T> List<T> toArray(String param, Class<T> type) {
        List<T> list = null;
        try {
            list = objectMapper.readValue(param, objectMapper.getTypeFactory().constructParametricType(ArrayList.class, type));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
